<template>
  <div class="product-analysis">
    <!-- Title section -->
    <div class="header-section">
      <h1 class="main-title">Product Data Analysis</h1>
      <p class="sub-title">
        This dashboard analyzes product-related data from time and product dimensions to adjust product category sales
        strategies.
      </p>
    </div>

    <!-- Content section -->
    <div class="content-section">
      <!-- Upper section -->
      <div class="upper-section">
        <!-- Time filter -->
        <div class="filter-section">
          <el-form :inline="true" :model="filterForm">
            <el-form-item>
              <el-date-picker
                v-model="filterForm.dateRange"
                type="daterange"
                range-separator="to"
                start-placeholder="Start Date"
                end-placeholder="End Date"
                value-format="YYYY-MM-DD"
                style="width: 260px" />
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button type="primary" @click="handleTimeFilter">
                  <el-icon>
                    <Search />
                  </el-icon>
                  Filter
                </el-button>
                <el-button @click="resetTimeFilter">
                  <el-icon>
                    <Refresh />
                  </el-icon>
                  Reset
                </el-button>
              </el-button-group>
            </el-form-item>
          </el-form>
        </div>

        <!-- Upper Charts area -->
        <el-row :gutter="20">
          <el-col :span="8" v-for="(chart, index) in upperCharts" :key="index">
            <el-card class="chart-card" shadow="hover">
              <div class="chart-title">{{ chart.title }}</div>
              <ECharts :options="chart.options" height="350px" />
            </el-card>
          </el-col>

          <!-- Product Category Sales 饼图部分 -->
          <el-col :span="8">
            <el-card class="chart-card" shadow="hover">
              <div class="chart-title">
                Product Category Sales
                <el-icon
                  class="chart-type-switch"
                  @click="togglePieChartType"
                  :title="getNextPieTypeTitle(pieChartType)">
                  <component :is="getPieChartTypeIcon(pieChartType)" />
                </el-icon>
              </div>
              <ECharts :options="getPieChartOptions" height="350px" />
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- Lower section -->
      <div class="lower-section">
        <!-- Product category filter -->
        <div class="filter-section">
          <el-form :inline="true" :model="filterForm">
            <el-form-item>
              <el-select
                v-model="filterForm.category"
                placeholder="Select Product Category"
                clearable
                style="width: 200px">
                <el-option
                  v-for="item in categories"
                  :key="item"
                  :label="item"
                  :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button type="primary" @click="handleCategoryFilter">
                  <el-icon>
                    <Search />
                  </el-icon>
                  Filter
                </el-button>
                <el-button @click="resetCategoryFilter">
                  <el-icon>
                    <Refresh />
                  </el-icon>
                  Reset
                </el-button>
              </el-button-group>
            </el-form-item>
          </el-form>
        </div>

        <!-- Lower Charts area -->
        <el-row :gutter="20">
          <el-col :span="8" v-for="(chart, index) in lowerCharts" :key="index">
            <el-card class="chart-card" shadow="hover">
              <div class="chart-title">
                {{ chart.title }}
                <el-icon
                  class="chart-type-switch"
                  @click="() => toggleChartType(index + upperCharts.length)"
                  :title="getNextTypeTitle(chartTypes[index + upperCharts.length])">
                  <component :is="getChartTypeIcon(chartTypes[index + upperCharts.length])" />
                </el-icon>
              </div>
              <ECharts :options="getChartOptions(chart, index + upperCharts.length)" height="350px" />
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { Search, Refresh, TrendCharts, DataLine, Histogram } from '@element-plus/icons-vue'
import ECharts from '@/components/ECharts.vue'
import { getFilterOptions, getProductAnalysis } from '@/api/analysis'
import { ElMessage } from 'element-plus'

// 筛选表单数据
const filterForm = reactive({
  dateRange: [],
  category: ''
})

// 产品类别选项
const categories = ref([])

// 图表类型数组
const CHART_TYPES = ['line', 'area', 'bar']
const PIE_CHART_TYPES = ['pie', 'ring', 'funnel']

// 图表类型状态
const chartTypes = ref(['line', 'line', 'line', 'line', 'line', 'line'])
const pieChartType = ref('pie')

// 获取下一个饼图类型的提示文字
const getNextPieTypeTitle = (currentType) => {
  switch (currentType) {
    case 'pie': return '切换为环形图'
    case 'ring': return '切换为漏斗图'
    case 'funnel': return '切换为饼图'
    default: return '切换图表类型'
  }
}

// 获取当前饼图类型的图标
const getPieChartTypeIcon = (type) => {
  switch (type) {
    case 'pie': return TrendCharts
    case 'ring': return DataLine
    case 'funnel': return Histogram
    default: return TrendCharts
  }
}

// 切换饼图类型
const togglePieChartType = () => {
  const currentIndex = PIE_CHART_TYPES.indexOf(pieChartType.value)
  const nextIndex = (currentIndex + 1) % PIE_CHART_TYPES.length
  pieChartType.value = PIE_CHART_TYPES[nextIndex]
}

const upperCharts2 = computed(() => [
  {
    title: 'Product Category Sales',
    options: {
      tooltip: {
        trigger: 'axis',
        formatter: params => `${params[0].name}<br/>${params[0].seriesName}: ${formatNumber(params[0].value)}`
      },
      legend: {
        data: ['Sales Volume']
      },
      grid: {
        left: '3%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartData.value.upperData.productTrend.months,
        axisLabel: {
          formatter: value => value.toLowerCase()
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => formatKNumber2(value)
        }
      },
      series: [
        {
          name: 'Sales Volume',
          type: 'line',
          data: chartData.value.upperData.productTrend.volumes
        }
      ]
    }
  }
])

// 获取饼图选项
const getPieChartOptions = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [{
      name: 'Product Category Sales',
      type: pieChartType.value === 'ring' ? 'pie' : pieChartType.value,
      radius: pieChartType.value === 'ring' ? ['40%', '70%'] : '70%',
      data: chartData.value.upperData.productShares?.map(item => ({
        name: item.category,
        value: item.salesAmount,
        percentage: item.percentage
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
})

// 获取下一个类型的提示文字
const getNextTypeTitle = (currentType) => {
  switch (currentType) {
    case 'line': return '切换为面积图'
    case 'area': return '切换为柱状图'
    case 'bar': return '切换为折线图'
    default: return '切换图表类型'
  }
}

// 获取当前图表类型的图标
const getChartTypeIcon = (type) => {
  switch (type) {
    case 'line': return TrendCharts
    case 'area': return DataLine
    case 'bar': return Histogram
    default: return TrendCharts
  }
}

// 切换图表类型
const toggleChartType = (index) => {
  const currentType = chartTypes.value[index]
  const currentIndex = CHART_TYPES.indexOf(currentType)
  const nextIndex = (currentIndex + 1) % CHART_TYPES.length
  chartTypes.value[index] = CHART_TYPES[nextIndex]
}

// 获取图表选项
const getChartOptions = (chart, index) => {
  if (!chart.options || !chart.options.series) {
    return {} // 返回一个空对象以避免错误
  }
  return {
    ...chart.options,
    series: chart.options.series.map(series => getSeriesConfig(chartTypes.value[index], series.data, series.name))
  }
}

// 获取图表配置
const getSeriesConfig = (type, data, name) => {
  const baseConfig = {
    name,
    data,
    symbolSize: 8
  }

  switch (type) {
    case 'bar':
      return {
        ...baseConfig,
        type: 'bar',
      }
    case 'area':
      return {
        ...baseConfig,
        type: 'line',
        areaStyle: {
          opacity: 0.8,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: name === 'Profit' ? 'rgba(103, 194, 58, 0.6)' : 'rgba(64, 158, 255, 0.6)'
            }, {
              offset: 1,
              color: name === 'Profit' ? 'rgba(103, 194, 58, 0.1)' : 'rgba(64, 158, 255, 0.1)'
            }]
          }
        }
      }
    case 'line':
    default:
      return {
        ...baseConfig,
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3
        },
        showSymbol: true
      }
  }
}

// 图表数据
const chartData = ref({
  // 上半部分数据（受日期影响）
  upperData: {
    topProducts: [],
    productShares: [],
    productTrend: {
      months: [],
      volumes: []
    }
  },
  // 下半部分数据（受类别影响）
  lowerData: {
    categoryTrend: {
      months: [],
      prices: [],
      profits: [],
      volumes: [],
      sales: []
    }
  }
})

// 获取筛选选项数据
const loadFilterOptions = async () => {
  try {
    const options = await getFilterOptions()
    categories.value = options.categories
    if (categories.value.length > 0) {
      filterForm.category = categories.value[0]
      await fetchUpperData()
    }
  } catch (error) {
    ElMessage.error('Failed to load filter options, please refresh the page')
  }
}

// 获取上半部分数据（基于日期筛选）
const fetchUpperData = async () => {
  try {
    const data = await getProductAnalysis({
      dateRange: filterForm.dateRange
    })
    if (data) {
      chartData.value.upperData = {
        topProducts: data.topProducts?.reverse() || [],
        productShares: data.productShares || [],
        productTrend: {
          months: data.productTrend?.months || [],
          volumes: data.productTrend?.volumes || []
        }
      }
    }
  } catch (error) {
    ElMessage.error('Failed to fetch time-based data, please try again')
  }
}

// 获取下半部分数据（基于类别筛选）
const fetchLowerData = async () => {
  try {
    const data = await getProductAnalysis({
      category: filterForm.category
    })
    if (data?.categoryTrend) {
      chartData.value.lowerData.categoryTrend = data.categoryTrend
    }
  } catch (error) {
    ElMessage.error('Failed to fetch category-based data, please try again')
  }
}

// 处理时间筛选
const handleTimeFilter = async () => {
  await fetchUpperData()
}

// 处理类别筛选
const handleCategoryFilter = async () => {
  await fetchLowerData()
}

// 重置时间筛选
const resetTimeFilter = () => {
  filterForm.dateRange = []
  fetchUpperData()
}

// 重置类别筛选
const resetCategoryFilter = () => {
  if (categories.value.length > 0) {
    filterForm.category = categories.value[0]
  } else {
    filterForm.category = ''
  }
  fetchLowerData()
}

// 上半部分图表配置
const upperCharts = computed(() => [
  {
    title: 'Product Category Sales Volume',
    options: {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: params => `${params[0].name}<br/>${params[0].seriesName}: ${formatNumber(params[0].value)}`
      },
      legend: {
        data: ['Sales']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => formatNumber(value)
        }
      },
      yAxis: {
        type: 'category',
        data: chartData.value.upperData.topProducts.slice(0, 5).map(item => item.category)
      },
      series: [
        {
          name: 'Sales',
          type: 'bar',
          data: chartData.value.upperData.topProducts.slice(0, 5).map(item => item.salesVolume)
        }
      ]
    }
  },
  {
    title: 'Product Category Sales',
    options: {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: params => `${params[0].name}<br/>${params[0].seriesName}: ${formatNumber(params[0].value)}`
      },
      legend: {
        data: ['Sales']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => `${formatKNumber(value)}`
        }
      },
      yAxis: {
        type: 'category',
        data: chartData.value.upperData.topProducts.slice(0, 5).map(item => item.category)
      },
      series: [
        {
          name: 'Sales',
          type: 'bar',
          data: chartData.value.upperData.topProducts.slice(0, 5).map(item => item.salesAmount)
        }
      ]
    }
  },
])

// 下半部分图表配置
const lowerCharts = computed(() => [
  {
    title: 'Average unit price and profit of products',
    options: {
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: ['Price', 'Profit']
      },
      grid: {
        left: '3%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartData.value.lowerData.categoryTrend.months,
        axisLabel: {
          formatter: value => value
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => formatKNumber2(value)
        }
      },
      series: [
        {
          name: 'Price',
          type: 'line',
          data: chartData.value.lowerData.categoryTrend.prices
        },
        {
          name: 'Profit',
          type: 'line',
          data: chartData.value.lowerData.categoryTrend.profits
        }
      ]
    }
  },
  {
    title: 'Product Category Sales Volume',
    options: {
      tooltip: {
        trigger: 'axis',
        formatter: params => `${params[0].name}<br/>${params[0].seriesName}: ${formatNumber(params[0].value)}`
      },
      legend: {
        data: ['Volume']
      },
      grid: {
        left: '3%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartData.value.lowerData.categoryTrend.months,
        axisLabel: {
          formatter: value => value
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => formatKNumber2(value)
        }
      },
      series: [
        {
          name: 'Volume',
          type: 'line',
          data: chartData.value.lowerData.categoryTrend.volumes
        }
      ]
    }
  },
  {
    title: 'Product Category Sales',
    options: {
      tooltip: {
        trigger: 'axis',
        formatter: params => `${params[0].name}<br/>${params[0].seriesName}: ${formatNumber(params[0].value)}`
      },
      legend: {
        data: ['Sales']
      },
      grid: {
        left: '3%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: chartData.value.lowerData.categoryTrend.months,
        axisLabel: {
          formatter: value => value
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => formatKNumber2(value)
        }
      },
      series: [
        {
          name: 'Sales',
          type: 'bar',
          data: chartData.value.lowerData.categoryTrend.sales
        }
      ]
    }
  }
])

// 格式化数字（完整显示）
const formatNumber = (value) => {
  if (!value) return '0'
  return new Intl.NumberFormat('zh-CN').format(value)
}

// 格式化数字（K/M/B）
const formatKNumber = (value) => {
  if (!value) return '0'
  if (value >= 1000000000) {
    return (value / 1000000000).toFixed(1) + 'B'
  }
  return (value / 1000000).toFixed(1)
}

const formatKNumber2 = (value) => {
  if (!value) return '0'
  if (value >= 1000) {
    return (value / 1000).toFixed(1) + 'K'
  }
  return value.toString()
}

onMounted(async () => {
  await loadFilterOptions()
  await Promise.all([fetchUpperData(), fetchLowerData()])
})
</script>

<style scoped>
.product-analysis {
  width: calc(100vw - 400px);
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.header-section {
  padding: 24px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2f3d;
  margin-bottom: 8px;
}

.sub-title {
  font-size: 14px;
  color: #5e6d82;
  margin: 0;
}

.content-section {
  padding: 24px;
}

.upper-section,
.lower-section {
  margin-bottom: 24px;
}

.filter-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #303133;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.chart-type-switch {
  cursor: pointer;
  font-size: 18px;
  color: #909399;
}

.chart-type-switch:hover {
  color: #409EFF;
  background-color: #ecf5ff;
}

:deep(.el-card__body) {
  padding: 0;
}

:deep(.el-card) {
  border-radius: 8px;
  border: none;
  transition: transform 0.3s;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
}

.filter-section :deep(.el-form--inline) {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-section :deep(.el-form-item) {
  margin-right: 0;
  margin-bottom: 0;
}

.filter-section :deep(.el-button-group) {
  display: flex;
  gap: 8px;
}

.filter-section :deep(.el-button) {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>